# -*- coding:utf-8 -*-
# @Time: 2020/9/10 9:56
# @Author: gupeng
# @File: article.py
# @Desc: 文章--hexists,hmset测试
from time import time


class Article:

    def __init__(self, client, article_id):
        self.client = client
        self.article_id = article_id
        self.article_hash = 'article::' + self.article_id

    def is_exists(self):
        """
        判断文章是否存在
        :return: 存在True，否则False
        """
        return self.client.hexists(self.article_hash, 'title')

    def create(self, title, content, author):
        """
        新增一篇文章
        :param title: 标题
        :param content: 内容
        :param author: 作者
        :return: True成功，False失败
        """
        if self.is_exists():
            return False
        article_data = {
            'title': title,
            'content': content,
            'author': author,
            'create_at': time()
        }
        return self.client.hmset(self.article_hash, article_data)

    def get(self):
        """
        返回文章各项信息
        :return: 文章各项信息
        """
        article_data = self.client.hgetall(self.article_hash)
        article_data['id'] = self.article_id
        return article_data

    def update(self, title=None, content=None, author=None):
        """
        更新文章信息
        :param title: 标题
        :param content: 内容
        :param author: 作者
        :return: 更新成功True，否则False
        """
        if not self.is_exists():
            return False
        article_data = {}
        if title is not None:
            article_data['title'] = title
        if content is not None:
            article_data['content'] = content
        if author is not None:
            article_data['author'] = author
        return self.client.hmset(self.article_hash, article_data)
